package it.unina.lab.anm.util;

import it.unina.lab.anm.InfoBusAnmApplication;
import it.unina.lab.anm.activity.SettingsActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.PreferenceManager;

public class PreferenceHelper {
	
	private static final String KEY_FIRST_LAUNCH_VERSION = "first_launch_version";
	
	private final SharedPreferences mPreferences;
	private final Context mContext;


	/**
	 * Constructor
	 */
	public PreferenceHelper() {
		mContext = InfoBusAnmApplication.getContext();
		mPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
	}
	
	
	public boolean isWelcomeQuoteEnabled() {
		return mPreferences.getBoolean(SettingsActivity.KEY_WELCOME_MESSAGE, SettingsActivity.KEY_WELCOME_MESSAGE_DEFAULT_VALUE);
	}
	
	
	public String getUserName() {
		return mPreferences.getString(SettingsActivity.KEY_YOUR_NAME, SettingsActivity.KEY_YOUR_NAME_DEFAULT_VALUE);
	}
	
	public String getDefaultLine() {
		return mPreferences.getString(SettingsActivity.KEY_DEFAULT_LINE, SettingsActivity.KEY_DEFAULT_LINE_DEFAULT_VALUE);
	}
	
    /**
     * Return a boolean representing that this is the first launch for this version
     */
	public boolean isFirstLaunchThisVersion() {
		long lastVersion = mPreferences.getLong(KEY_FIRST_LAUNCH_VERSION, 0);
		
		try {
			PackageInfo pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
			if (lastVersion < pi.versionCode) {
				return true;
			}
		} catch (NameNotFoundException e) {
			// Nothing
		}
		
		return false;
	}
	
    /**
     * Set a long signalling the lastest version of the application launched
     */	
	public void setFirstLaunchThisVersion() {
		
		try {
			PackageInfo pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
			SharedPreferences.Editor editor = mPreferences.edit();
			editor.putLong(KEY_FIRST_LAUNCH_VERSION, pi.versionCode);
			editor.commit();
		} catch (NameNotFoundException e) {
			// Nothing
		}
	}	

   
	
}
